package cmd

import (
	"encoding/json"
	"fmt"
	"gitee.com/daka1004/devops-runner/common/logs"
	"gitee.com/daka1004/devops-runner/init/router"
	"log"
	"net/http"
	"os"
	"path/filepath"

	"gitee.com/daka1004/devops-runner/modules/process"
	"gitee.com/daka1004/devops-runner/modules/setting"
	//"github.com/gin-gonic/gin"
	"time"
)

type Config struct {
	IP   string `json:"ip"`
	Port int    `json:"port"`
}

// Run 启动服务
func Run() {
	if process.IsPortInUse(setting.Setting.ServerPort) {
		log.Fatalf("Port 34567 is already in use")
		logs.Info("Port 34567 is already in use")
	}
	//Routers := gin.Default()
	//db.InitDB()
	//url := fmt.Sprintf("ws://%s:%d/ssh/agentLogger?executingId=%s", setting.Setting.ServerIP, 8280, req.ExecuteID)
	//url := fmt.Sprintf("ws://%s:%d/ssh/logger?nodeUUID=%s&executeLoggerUUID=%s", setting.Setting.ServerIP, 8280, req.NodeUuid, req.ExecuteID)
	// mq.InitWebSocketManager(url)
	//logs.Infof("url is : %v\n", url)
	// 心跳检测
	//go heartbeat()

	//gin.Run("/pipelineId/execute", executePipeline)
	//http.HandleFunc("/pipelineId/execute", executePipeline)

	// 3. 写入配置文件
	//port := "34567"
	//addr := fmt.Sprintf("%s:%s", setting.ServerIP, setting.ServerPort)

	/*if err := writeConfig(setting.Setting.ServerIP, setting.Setting.ServerPort); err != nil {
		fmt.Printf("写入配置文件失败: %v\n", err)
		return
	}*/
	//log.Fatal(http.ListenAndServe(":34567", nil))
	log.Printf("Starting runner on port %d", setting.Setting.ServerPort)
	logs.Infof("Starting runner on port %d", setting.Setting.ServerPort)
	_ = router.Router().Run(fmt.Sprintf(":%d", setting.Setting.ServerPort))

	//_ = router.Router().Run(":%d", setting.ServerPort)
	//_ = router.Router().Run(addr)
}

func heartbeat() {
	ticker := time.NewTicker(10 * time.Second)
	defer ticker.Stop()

	for range ticker.C {
		_, err := http.Get(fmt.Sprintf("http://%s:18080/test/heartbeat", setting.Setting.ServerIP))
		fmt.Println("---------------heartbeat-----------")
		if err != nil {
			log.Printf("Heartbeat failed: %v", err)
		}
	}
}

func writeConfig(ip string, port int) error {
	// 获取当前可执行文件所在目录
	exeDir, err := os.Executable()
	fmt.Println("获取当前可执行文件所在目录", exeDir)
	if err != nil {
		return fmt.Errorf("获取可执行文件路径失败: %w", err)
	}
	dir := filepath.Dir(exeDir)

	// 构造配置数据
	config := Config{
		IP:   ip,
		Port: port,
	}

	// 序列化为JSON
	data, err := json.MarshalIndent(config, "", "  ")
	if err != nil {
		return fmt.Errorf("JSON序列化失败: %w", err)
	}

	// 写入文件
	configPath := filepath.Join(dir, "conf.json")
	if err := os.WriteFile(configPath, data, 0644); err != nil {
		return fmt.Errorf("写入文件失败: %w", err)
	}

	return nil
}
